package com.tx.admin.charartertag.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.tx.admin.tagrelate.pojo.dto.TagRelateListDTO;
import com.tx.admin.tagrelate.pojo.po.TagRelate;
import com.tx.admin.tagrelate.pojo.vo.TagRelateVO;
import com.tx.admin.tagrelate.service.TagRelateService;
import com.tx.core.util.*;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.tx.admin.charartertag.service.ChararterTagService;
import com.tx.admin.charartertag.pojo.po.ChararterTag;
import com.tx.admin.charartertag.mapper.ChararterTagMapper;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.core.query.QueryChain;
import com.tx.core.common.enums.CommonResponseEnum;
import com.tx.core.common.entity.PageResult;
import com.tx.core.common.entity.SelectIdsDTO;
import java.io.Serializable;
import java.util.*;

import com.tx.admin.charartertag.pojo.dto.ChararterTagCreateDTO;
import com.tx.admin.charartertag.pojo.dto.ChararterTagUpdateDTO;
import com.tx.admin.charartertag.pojo.dto.ChararterTagListDTO;
import com.tx.admin.charartertag.pojo.dto.ChararterTagImportDTO;
import com.tx.core.common.entity.ImportExcelDTO;
import com.tx.excel.core.ExcelResult;
import java.io.OutputStream;
import java.util.function.Function;
import java.util.stream.Collectors;

import jakarta.servlet.http.HttpServletResponse;
import com.tx.excel.utils.ExcelUtils;
import lombok.SneakyThrows;
import com.tx.admin.charartertag.pojo.vo.ChararterTagVO;

/**
 * <p>
 * 人物标签表 服务实现类
 * </p>
 *
 * @author sz-admin
 * @since 2025-05-04
 */
@Service
@RequiredArgsConstructor
public class ChararterTagServiceImpl extends ServiceImpl<ChararterTagMapper, ChararterTag> implements ChararterTagService {

    @Autowired
    private TagRelateService tagRelateService;

    @Override
    public void create(ChararterTagCreateDTO dto){
        ChararterTag chararterTag = BeanCopyUtils.copy(dto, ChararterTag.class);
        save(chararterTag);
    }

    @Override
    public void update(ChararterTagUpdateDTO dto){
        ChararterTag chararterTag = BeanCopyUtils.copy(dto, ChararterTag.class);
        QueryWrapper wrapper;
        // id有效性校验
        wrapper = QueryWrapper.create()
            .eq(ChararterTag::getId, dto.getId());
        CommonResponseEnum.INVALID_ID.assertTrue(count(wrapper) <= 0);

        saveOrUpdate(chararterTag);
    }

    @Override
    public PageResult<ChararterTagVO> page(ChararterTagListDTO dto){
        Page<ChararterTagVO> page = pageAs(PageUtils.getPage(dto), buildQueryWrapper(dto), ChararterTagVO.class);
        return PageUtils.getPageResult(page);
    }

    @Override
    public List<ChararterTagVO> list(ChararterTagListDTO dto){
        return listAs(buildQueryWrapper(dto), ChararterTagVO.class);
    }

    @Override
    public void remove(SelectIdsDTO dto){
        CommonResponseEnum.INVALID_ID.assertTrue(dto.getIds().isEmpty());
        removeByIds(dto.getIds());
    }

    @Override
    public ChararterTagVO detail(Object id){
        ChararterTag chararterTag = getById((Serializable) id);
        CommonResponseEnum.INVALID_ID.assertNull(chararterTag);
        return BeanCopyUtils.copy(chararterTag, ChararterTagVO.class);
    }

    @SneakyThrows
    @Override
    public void importExcel(ImportExcelDTO dto) {
        ExcelResult<ChararterTagImportDTO> excelResult = ExcelUtils.importExcel(dto.getFile().getInputStream(), ChararterTagImportDTO.class, true);
        List<ChararterTagImportDTO> list = excelResult.getList();
        List<String> errorList = excelResult.getErrorList();
        String analysis = excelResult.getAnalysis();
        System.out.println(" analysis : " + analysis);
        System.out.println(" isCover : " + dto.getIsCover());
    }

    @SneakyThrows
    @Override
    public void exportExcel(ChararterTagListDTO dto, HttpServletResponse response) {
        List<ChararterTagVO> list = list(dto);
        String fileName = "人物标签表模板";
        OutputStream os = FileUtils.getOutputStream(response, fileName + ".xlsx");
        ExcelUtils.exportExcel(list, "人物标签表", ChararterTagVO.class, os);
    }

    @Override
    public List<TagRelateVO> detailTagList(TagRelateListDTO dto) {
        List<TagRelateVO> list = tagRelateService.list(dto);
        if (CollUtil.isEmpty(list)){
            return new ArrayList<>();
        }
        List<Long> tagIds = list.stream().map(TagRelateVO::getTagId).collect(Collectors.toList());
        QueryWrapper wrapper = QueryWrapper.create().from(ChararterTag.class);
        List<ChararterTag> tags = list(wrapper.in(ChararterTag::getId, tagIds));
        Map<Long, ChararterTag> idTagMap = Optional.ofNullable(tags).orElse(new ArrayList<>()).stream()
                .collect(Collectors.toMap(ChararterTag::getId, Function.identity()));

        list.forEach(s->{
            ChararterTag tag = idTagMap.getOrDefault(s.getTagId(), new ChararterTag());
            s.setColor(tag.getColor());
            s.setColorName(tag.getColorName());
            s.setDescribe(tag.getDescribe());
            s.setRemark(tag.getRemark());
        });

        return list;
    }

    @Override
    public void batchSaveRelative(List<TagRelateVO> vos) {
        List<TagRelate> collect = vos.stream().map(s -> {
            TagRelate relate = new TagRelate();
            relate.setId(null);
            relate.setBelongType(s.getBelongType());
            relate.setBusId(s.getBusId());
            relate.setTagId(s.getTagId());
            return relate;
        }).collect(Collectors.toList());

        QueryWrapper wrapper = QueryWrapper.create().from(TagRelate.class);

        //全删再增
        tagRelateService.remove(wrapper.eq(TagRelate::getBusId,vos.get(0).getBusId()));
        tagRelateService.saveBatch(collect);
    }

    @Override
    public List<ChararterTagVO.TagEnum> remoteSearch(String keyword) {
        QueryWrapper wrapper = QueryWrapper.create().from(ChararterTag.class);
        wrapper.like(ChararterTag::getDescribe,keyword,StringUtils.isNotEmpty(keyword))
                .eq(ChararterTag::getTagType,1);
        List<ChararterTag> list = list(wrapper);
        List<ChararterTagVO.TagEnum> result = Optional.ofNullable(list).orElse(new ArrayList<>()).stream().map(s -> {
            ChararterTagVO.TagEnum tag = new ChararterTagVO.TagEnum();
            tag.setId(s.getId());
            tag.setTagName(s.getDescribe());
            tag.setColor(s.getColor());
            return tag;
        }).collect(Collectors.toList());

        return result;
    }

    private static QueryWrapper buildQueryWrapper(ChararterTagListDTO dto) {
        QueryWrapper wrapper = QueryWrapper.create().from(ChararterTag.class);
        //传的中文进来就不改了
        if (Utils.isNotNull(dto.getColor())) {
            wrapper.eq(ChararterTag::getColorName, dto.getColor());
            //wrapper.eq(ChararterTag::getColor, dto.getColor());
        }
//        if (Utils.isNotNull(dto.getColorName())) {
//            wrapper.eq(ChararterTag::getColorName, dto.getColorName());
//        }
        if (Utils.isNotNull(dto.getDescribe())) {
            wrapper.like(ChararterTag::getDescribe, dto.getDescribe());
        }
        if (Utils.isNotNull(dto.getTagType())) {
            wrapper.eq(ChararterTag::getTagType, dto.getTagType());
        }
        return wrapper;
    }
}